package com.yfree.utils.net;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class YNetUtil {
    // 使用前配置权限
    // <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    // 判断是否处于网络中
    private static boolean isNetWorkConnected(Activity context) {
        NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isAvailable();
    }

    // 判断是否处于Wifi
    private static boolean isWifi(Activity context) {
        NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return networkInfo != null && networkInfo.isAvailable();
    }

    // 判断是否处于Mobile网络
    private static boolean isMobile(Activity context) {
        NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        return networkInfo != null && networkInfo.isAvailable();
    }

    // 获取网络类型
    public static int getNetType(Activity context) {
        NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        return networkInfo != null ? networkInfo.getType() : -1;
    }

    public static boolean isNetAble(Activity context) {
        return (isWifi(context) || isMobile(context)) && isNetWorkConnected(context);
    }
}
